package com.zp.resource.psychological;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;
import com.zp.bean.common.ResultCommonVo;
import com.zp.bean.psychological.BaseServiceVo;
import com.zp.bean.psychological.ResultBaseServiceVo;
import com.zp.bean.psychological.ResultServiceVo;
import com.zp.bean.psychological.ServiceVo;
import com.zp.domain.Organization;
import com.zp.domain.Service;
import com.zp.resource.common.BaseServices;
import com.zp.util.Constant;
import com.zp.util.MyException;

/**
 * service services
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/3/8
 * 
 */
@Component
@Path("/rest/service")
@Singleton
public class ServiceServices extends BaseServices {

	/**
	 * add one Service path:/service/addService Http:POST
	 * 
	 * @param service
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@POST
	@Path("/addService")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addService(Service service) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.save(service);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * update one Service path:/service/updateService Http:PUT
	 * 
	 * @param service
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@PUT
	@Path("/updateService")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateService(Service service) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.update(service);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * delete Service by id path:/service/deleteService Http:DELETE
	 * 
	 * @param serviceId
	 *            primary key of Service
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@DELETE
	@Path("/deleteService")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteService(@QueryParam("serviceId") String serviceId) {
		logger.info("deleteService called serviceId:" + serviceId);
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.deleteById(Service.class, serviceId);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get Service by id path:/service/getService Http:POST
	 * 
	 * @param serviceId
	 *            primary key of Service
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0,"vo":{"id":
	 *         "402881e544a211e70144a2126c3a0001"
	 *         ,"title":"心理减压公益服务","titleImage"
	 *         :null,"organizationName":null,"introduce"
	 *         :"心理减压是一种高效整合的心理咨询","duration"
	 *         :1,"content":"心理减压是一种高效整合的心理咨询","organization"
	 *         :{"id":"402880e44492d4ac014492d533850001"
	 *         ,"name":"四川大学青年志愿者协会","image"
	 *         :null,"summary":"四川大学青少年行动起始于","introduce"
	 *         :"四川大学青少年行动起始于1994年3月...."
	 *         ,"address":"四川省成都市武侯区科华路","character":"非营利性组织"
	 *         ,"manage":"四川大学团委","cityCode"
	 *         :"028","phone":"028-88888888","weibo"
	 *         :"http://weibo.com/schxyx","members":150}},"list":null}
	 */
	@POST
	@Path("/getService")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getServiceById(@QueryParam("serviceId") String serviceId) {
		logger.info("deleteService called serviceId:" + serviceId);
		ResultServiceVo result = new ResultServiceVo();
		String jpql = "from Service s,Organization o where s.organization=o.id and s.id=?";
		List<?> list = null;
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);

		try {
			Object[] param = { serviceId };
			list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, param);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}

		if (list != null && list.size() > Constant.ZERO) {

			Object[] data = (Object[]) list.get(Constant.ZERO);
			ServiceVo vo = new ServiceVo();
			Service service = (Service) data[Constant.ZERO];
			vo.setContent(service.getContent());
			vo.setDuration(service.getDuration());
			vo.setId(service.getId());
			vo.setTitle(service.getTitle());
			vo.setIntroduce(service.getIntroduce());
			vo.setOrganization((Organization) data[Constant.ONE]);
			vo.setTitleImage(service.getTitleImage());
			result.setVo(vo);

		}
		return Response.ok(result).build();
	}

	/**
	 * 
	 * get service for one organization path:/service/getServices Http:POST
	 * 
	 * @param pageNo
	 * 
	 * @param pageSize
	 * 
	 * @param organizationId
	 *            if ignore the default value will be null
	 * 
	 * 
	 * @return Response, ResultBaseServiceVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1,"list":[{"id":
	 *         "402881e544a211e70144a2126c3a0001"
	 *         ,"title":"心理减压公益服务","titleImage"
	 *         :"null","organizationName":"四川大学青年志愿者协会"
	 *         ,"introduce":"心理减压是一种高效整合的心理咨询","duration":1}]}
	 */
	@POST
	@Path("/getServices")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getServicesByOrg(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("organizationId") String organizationId) {
		logger.info("getServices called json pageNo:" + pageNo + " pageSize:"
				+ pageSize);
		String jpql = "select s.id,o.name,s.introduce,s.duration,s.titleImage,s.title from Service s,Organization o where s.organization=o.id and o.id=?";
		String countSql = "select count(s.id) from Service s,Organization o where s.organization=o.id and o.id=?";
		List<?> list = null;
		ResultBaseServiceVo result = new ResultBaseServiceVo();
		List<BaseServiceVo> lt = new ArrayList<BaseServiceVo>();
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);
		if ("".equals(organizationId) || organizationId == null) {
			try {
				jpql = "select s.id,o.name,s.introduce,s.duration,s.titleImage,s.title from Service s,Organization o where s.organization=o.id";
				countSql = "select count(s.id) from Service s,Organization o where s.organization=o.id";
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, null);
				long totalCount = this.jpaDao.getCount(countSql, null);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}
		} else {

			try {
				Object[] params = { organizationId };
				list = this.jpaDao
						.getResultData(pageNo, pageSize, jpql, params);
				long totalCount = this.jpaDao.getCount(countSql, params);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}

		}

		if (list != null && list.size() > Constant.ZERO) {
			for (Object o : list) {
				Object[] data = (Object[]) o;
				BaseServiceVo vo = new BaseServiceVo();
				vo.setId(String.valueOf(data[Constant.ZERO]));
				vo.setOrganizationName(String.valueOf(data[Constant.ONE]));
				vo.setIntroduce(String.valueOf(data[Constant.TWO]));
				vo.setDuration(Integer.valueOf(String
						.valueOf(data[Constant.THREE])));
				vo.setTitleImage(String.valueOf(data[Constant.FOUR]));
				vo.setTitle(String.valueOf(data[Constant.FIVE]));
				lt.add(vo);
			}
			result.setList(lt);

		}
		return Response.ok(result).build();
	}
}
